// pages/my-pages/voucher-add/index.js
const httpUtils = require('../../../utils/httpUtils')
const ui = require('../../../utils/ui')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: -1,
    voucher: {},
    itemList: [],
    itemSize: 0,
    start: '2020-01-01 00:00:00',
    end: '2050-09-09 23:59:59',
    pickerTitle: '生效时间',
    dateVisible: false,
    pickerMode: "date",
    dateText: '',
    pickerFormat: "YYYY-MM-DD",
    selectDateType: 1
  },

  //点击了保存按钮
  confirmSaveButton: function () {
    let that = this;
    let obj;
    if (-1 == that.data.id) {
      obj = {
        method: 'POST',
        showLoading: true,
        url: 'voucher/addVoucher',
        data: that.data.voucher
      }
    } else {
      obj = {
        method: 'POST',
        showLoading: true,
        url: 'voucher/updateVoucher',
        data: that.data.voucher
      }
    }
    httpUtils.request(obj).then(res => {
      if (res.data.retCode == 0) {
        ui.showToast('保存成功')
        wx.navigateBack({
          detail: 1
        })
      } else {
        ui.showToast(res.data.message)
      }
    }).catch(err => {
      ui.showToast('请求失败')
    });
  },

  //点击查询日期, 弹出日期选择
  showPicker: function (e) {
    this.setData({
      dateVisible: true
    })
  },

  //打开生效时间选择器
  changeValidityStart: function () {
    let that = this;
    let showDateText = '';
    let id = that.data.id;
    if (-1 == id || null == id) {
      showDateText = that.formaData(new Date());
    } else {
      showDateText = that.data.voucher.validityStart
    }
    that.setData({
      pickerTitle: '生效时间',
      dateText: showDateText,
      selectDateType: 1
    });
    that.showPicker();
  },

  //打开到期时间选择器
  changeValidityEnd: function () {
    let that = this;
    let showDateText = '';
    let id = that.data.id;
    if (-1 == id || null == id) {
      showDateText = that.formaData(new Date());
    } else {
      showDateText = that.data.voucher.validityEnd
    }
    this.setData({
      pickerTitle: '到期时间',
      dateText: showDateText,
      selectDateType: 2
    });
    that.showPicker();
  },

  //日期选择确定按钮
  onConfirm: function (e) {
    let that = this;
    const {
      value
    } = e.detail;
    let selectType = that.data.selectDateType;
    if (selectType == 1) {
      this.setData({
        'voucher.validityStart': value,
      });
    } else {
      this.setData({
        'voucher.validityEnd': value,
      });
    }
    this.hidePicker();
  },

  //日期选择弹窗改变事件
  onColumnChange: function (e) {
    console.log('选择时间:', e.detail.value);
  },

  //日期选择弹窗取消按钮
  hidePicker: function () {
    this.setData({
      dateVisible: false
    })
  },

  //代金券名称输入改变
  inputvoucherName: function (e) {
    this.setData({
      'voucher.voucherName': e.detail.value
    })
  },

  //代金券金额改变
  inputDefaultPrice: function (e) {
    let defaultPrice = e.detail.value;
    defaultPrice = defaultPrice.replace(/\D/g, '')
    this.setData({
      'voucher.voucherAmount': defaultPrice
    })
  },

  //改变基础项目选中数量
  setSelectSize: function () {
    let that = this;
    let selectList = that.data.itemList;
    if (undefined != selectList) {
      that.setData({
        itemSize: selectList.length,
        'voucher.itemList': selectList
      })
    }
  },

  //点击了删除按钮
  onDelete: function (e) {
    this.setData({
      ['showTextAndTitleWithInput']: true
    })
  },

  //点击删除弹窗的确定
  confirmChangeMember: function (e) {
    let that = this;
    let id = that.data.id;
    let obj = {
      method: 'GET',
      showLoading: false,
      url: 'voucher/delVoucher?id=' + id
    }
    httpUtils.request(obj).then(res => {
      console.log(res.data.message)
      if (res.data.retCode == 0) {
        wx.navigateBack({
          detail: 1
        })
      } else {
        ui.showToast(res.data.message)
      }
    }).catch(err => {
      ui.showToast('请求失败')
    });
  },

  //点击删除弹窗的取消
  closeDialog: function () {
    this.setData({
      ['showTextAndTitleWithInput']: false
    });
  },

  //查询代金券信息
  getVoucherFunc: function () {
    let that = this;
    let id = that.data.id;
    if (-1 == id || null == id) {
      that.setData({
        voucher: {}
      })
    } else {
      //获取代金券信息
      let obj = {
        method: 'GET',
        showLoading: false,
        url: 'voucher/getVoucherById?id=' + id
      }
      httpUtils.request(obj).then(res => {
        console.log(res.data.message)
        if (res.data.retCode == 0) {
          this.setData({
            voucher: res.data.data,
            itemList: res.data.data.itemList
          })
          this.setSelectSize();
        } else {
          ui.showToast(res.data.message)
        }
      }).catch(err => {
        ui.showToast('请求失败')
      });
    }
  },

  //跳转可用范围选择
  checkItemButton: function (e) {
    console.log('点击了可用范围选择')
    wx.navigateTo({
      url: '/pages/my-pages/select-item/index',
    })
  },

  //时间格式化
  formaData: function (timer) {
    let that = this;
    const year = timer.getFullYear()
    const month = timer.getMonth() + 1 // 由于月份从0开始，因此需加1
    const day = timer.getDate()
    return `${that.pad(year, 4)}-${that.pad(month)}-${that.pad(day)}`
  },

  // 定义具体处理标准
  // timeEl 传递过来具体的数值：年月日时分秒
  // total 字符串总长度 默认值为2
  // str 补充元素 默认值为"0"
  pad: function (timeEl, total = 2, str = '0') {
    return timeEl.toString().padStart(total, str)
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      id: options.id,
      voucher: {}
    });
    this.getVoucherFunc();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.setSelectSize();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})